<template>
  <div id="detail" ref="detail">
    <div class="input" :class="inputActive ? 'inputActive' : ''">
      <el-form :model="inputData" inline :rules="rules" label-width="80px" ref="from"
        >
        <template v-for="(i, arrId) in config">
          <template v-for="(item, index) in i">
            <el-form-item :key="arrId + '-' + index" :label="item.label" :prop="item.props"
              v-if="['input', 'map', 'address'].includes(item.type)"
              >
              <el-input :type="item.inputType ? item.inputType : 'text'" :disabled="item.disabled"
                @change="getData(item.props, inputData[item.props], item.type)"
                v-model="inputData[item.props]"></el-input>
            </el-form-item>
            <el-form-item :key="arrId + '-' + index" :label="item.label" :prop="item.props"
              v-else-if="item.type == 'table'">
              <el-autocomplete :disabled="item.disabled" @select="$event => selectData($event,item,index)" :fetch-suggestions="(qs,cb) => querySearch(item,qs,cb)" :value-key="item.props"
                v-model="inputData[item.props]" :readonly='item.readonly'>
                <!-- readonly,控制组件只读,true为只读,不填 或者false则可以输入 -->
                <i v-if="!item.disabled" @click.stop="setPop($event, index, item, arrId)"
                  class="el-input__icon el-icon-search" slot="suffix" style="cursor: pointer;"></i>
              </el-autocomplete>
            </el-form-item>
            <el-form-item :key="arrId + '-' + index" :label="item.label" :prop="item.props"
              v-else-if="item.type == 'select'" >
              <el-select v-if="item.multiple" :disabled="item.disabled" :multiple="true"
                :placeholder="$t('common.select')" v-model="multiValues[item.id]"
                @change="getMultiData(item.props, inputData, item.id)">
                <el-option v-for="(i, idx) in item.options" :disabled="i.disabled" :key="idx"
                  :value="i.description"></el-option>
              </el-select>
              <el-select v-else :disabled="item.disabled" filterable
                @change="getData(item.props, inputData[item.props], item.type)" :placeholder="$t('common.select')"
                v-model.String="inputData[item.props]">
                <el-option label="     " value=""></el-option>
                <el-option :disabled="i.disabled" :key="i.code" :label="i.description" :value="i.code"
                  v-for="(i, idx) in item.options"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :key="arrId + '-' + index" :label="item.label" :prop="item.props"
              v-else-if="item.type == 'date'">
              <el-date-picker :disabled="item.disabled" :picker-options="pickerOptions"
                @change="getData(item.props, inputData[item.props], item.type)" placeholder type="datetime"
                v-model="inputData[item.props]" value-format="timestamp">
              </el-date-picker>
            </el-form-item>
            <el-form-item :key="arrId + '-' + index" :label="item.label" :prop="item.props"
              v-else-if="item.type == 'cascader'">
              <el-cascader :ref="item.props + 'Ref'" :disabled="item.disabled" v-model="inputData[item.props]"
                :options="item.options" :show-all-levels="false"
                @change="getData(item.props, inputData[item.props], item.type)" :props="{ ...item.attr }"></el-cascader>
            </el-form-item>
            <el-form-item :key="arrId + '-' + index" :label="item.label" :prop="item.props"
              v-else-if="item.type == 'textarea'" >
              <el-input :disabled="item.disabled" :style="{ height: item.height }"
                @change="getData(item.props, inputData[item.props], item.type)" placeholder type="textarea"
                v-model="inputData[item.props]"></el-input>
            </el-form-item>
            <el-form-item :key="arrId + '-' + index" :prop="item.props" label="   " v-else-if="item.type == 'checkbox'">
              <el-checkbox :style="{ opacity: item.hidden }" style="line-height: 40px" :disabled="item.disabled"
                @change="getData(item.props, inputData[item.props], item.type)" :false-label="0" :true-label="1"
                v-model="inputData[item.props]">
                {{ item.label }}
              </el-checkbox>
            </el-form-item>
            <div class="titleLabel" v-html="item.label" v-else-if="item.type == ''" :key="arrId + '-' + index">
            </div>
          </template>
        </template>

      </el-form>
    </div>
    <el-dialog :modal="false" :visible.sync="dialogTableVisible" title="" top="0" v-dialogDrag
      :close-on-click-modal="false" width="700px">
      <v-table :checked="false" :hasEdit="false" :height="'270px'" :pageSize="popPageSize" :right="true"
        :tableConfig="popTableConfig" :page="page" :tableData="popTableData" :total="popTotal" @searhData="searhData"
        @findData="getPopTableData" @amend="popAmend" @upData="getPopTableData"
        @getTableData="getPopTableData"></v-table>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import table from "./Table";
import baseMixin from "@/mixins/BaseMixin";
import bus from "../../bus/bus";
export default {
  name: "",
  mixins: [baseMixin],
  props: {
    inputConfig: {
      type: Array
    },
    detailData: {
      type: Object
    },
    rules: {
      type: Object
    },
    inputActive: {
      type: Boolean,
      default: false,
    }

  },
  data() {
    return {
      config: [],
      value: "",
      getTableProp: "",
      newData: {},
      clickId: '',
      num: 0,
      selectArr: [],


      dialogTableVisible: false,
      popflag: true,
      popTableConfig: [],
      popPageSize: 100,
      page: 1,
      popTotal: 1000,
      popTableData: [],
      popUrl: "",
      popClickId: "",
      popName: "",
      listId: "",
      tableSearhData: {},
      multiValues: {},
      pickerOptions: {
        shortcuts: [{
          text: this.$t('app.today'),
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: this.$t('app.lastday'),
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: this.$t('app.lastweek'),
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
    };
  },
  computed: {
    inputData() {
      let id = [];
      if (this.inputConfig.length > 1) {
        this.inputConfig.forEach((item) => {
          item.forEach(i => {
            if (i.type === 'checkbox') {
              id.push(i.props);
            }
            if (i.type === 'select' && i.multiple) {
              if (i.default && i.default.length) {
                this.multiValues[i.id] = i.default
              }
            }
          })
        });
      }
      id.forEach(item => {
        if (this.$props.detailData[item]) {
          this.$props.detailData[item] = Number(this.$props.detailData[item]);
        }
      });
      this.selectArr.forEach(item => {
        if (this.$props.detailData[item]) {
          this.$props.detailData[item] = String(this.$props.detailData[item]);
        }
      })
      return this.$props.detailData
    }
  },
  created() {
  },
  methods: {
    setPop(e, id, item, arrid) {
      let pop = document.getElementsByClassName("el-dialog");
      if (!this.dialogTableVisible) {
        this.popTableConfig = item.tableConfig;
        this.popClickId = id;
        this.listId = arrid;
        this.popUrl = item.url;
        this.getPopTableData(1, {});
        pop[pop.length - 1].style.left = 211 + "px";
        pop[pop.length - 1].style.top = 127 + "px";
        this.dialogTableVisible = true;
      }
    },
    querySearch(item,queryString,cb){
      if(!queryString){
        return
      }
      if(Array.isArray(item.filterKey)){
        let params = {};
        item.filterKey.forEach(key => {
          params[key] = queryString
        })
        this.popUrl = item.filterUrl;
        this.$post(this.popUrl + '/' + queryString).then(res => {
          cb(res.data)
        })
      }else if(typeof(item.filterKey) == 'string'){
        let params = {};
        params[item.filterKey||item.props] = queryString;
        this.popUrl = item.url;
        this.getPopTableData(1,params).then(arr => {
          cb(arr)
        })
      }else{
        cb([])
      }
    },
    async getPopTableData(page, data) {
      let url = "";
      if(this.popUrl.includes('/?')){
        url = this.popUrl.replace('/?',`/${page}`);
      }else if(this.popUrl.endsWith('/')){
        url = this.popUrl + page
      }else{
        url = this.popUrl
      }
      try {
        let res = await this.$api.post(url, data);
          const data = res.page || res.data || res.bean;
          this.popTableData = data?.list;
          this.page = data?.curPage;
          this.popPageSize = data?.pageSize;
          this.popTotal = data?.total;
      } catch (e) {
        this.popTableData = [];
        this.page = 1;
        this.popPageSize = 1;
        this.popTotal = 1;
        this.$message.error(e);
      }
    },
    popAmend(index) {
      this.$emit('pop', this.popTableData[index], this.popClickId, (flag) => {
        this.dialogTableVisible = flag
      }, this.listId);
    },
    selectData(value,item,index){
      this.$emit(
        "pop",
        value,
        index,
        (flag) => {
          this.dialogTableVisible = flag;
        },
        item.props
      );
    },
    getData(prop, val, type) {
      let nodeData = {}
      if (type === "select") {
        if (this.rules) {
          if (this.rules[prop]) {
            if (val != "") {
              this.inputData[prop] = val;
            }
          } else {
            if (val === "") {
              this.inputData[prop] = " ";
            } else {
              this.inputData[prop] = val;
            }
          }
        }
      }
      if (val != '') {
        this.newData[prop] = val;
      } else {
        delete this.newData[prop];
      }
      if (type == 'cascader') {
        if (this.$refs[prop + 'Ref']) {
          if (Array.isArray(this.$refs[prop + 'Ref'])) {
            nodeData = this.$refs[prop + 'Ref'][0].getCheckedNodes();
          } else {
            nodeData = this.$refs[prop + 'Ref'].getCheckedNodes();
          }
        }
      }
      this.$emit('changeData', this.newData, prop, val, nodeData);
    },
    getMultiData(prop, val, type) {
      if (val[prop]) {
        this.inputData[prop] = this.multiValues[type]
      }
    },
    searhData(data, up) {
      if (!up) {
        this.tableSearhData = data;
      } else {
        this.tableSearhData = data;
        this.getPopTableData(1, this.tableSearhData);
      }
    },
    submitForm(formName) {
      let flag
      this.$refs[formName].validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });
      return flag;
    },
  },

  watch: {
    inputConfig: {
      handler(data) {
        this.selectArr = []
        if (data.length > 1) {
          data.forEach(item => {
            item.forEach(i => {
              if (i.type == "select") {
                this.selectArr.push(i.props)
              }
            })
          });
        }
        this.config = data;
        this.$props.detailData = this.$props.detailData

      },
      deep: true,
      immediate: true,
    },
    dialogTableVisible(data) {
      if (!data) {
        bus.$emit("clearSearhData");
        this.popTableConfig = [];
      }
    }
  },
  components: {
    "v-table": table
  }
}
  ;
</script>

<style scoped>
#detail {
  width: 100%;
  height: calc(100% - 31px);
}

.input {
  width: 100%;
}

.input:after {
  display: block;
  content: "";
  clear: both;
}

.el-form-item {
  /*min-height: 50px;*/
  margin-right: 6px;
}

.inputActive .el-form-item {
  width: auto;
}

.el-form-item__label {
  padding: 0px !important;
  line-height: 30px;
}

.el-form-item__content {
  line-height: 30px !important;
}

.el-input {
  height: 26px;
}

.el-form-item__label {
  font-size: 12px;
  line-height: 30px;
}

.titleLabel {
  padding: 0px 28px 0px 28px;
  height: 50px;
  font-size: 14px;
  line-height: 50px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.inputActive .titleLabel {
  padding: 0px 14px 0px 14px;
  height: 26px;
  font-size: 14px;
  line-height: 26px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.inputActive .el-checkbox {
  line-height: 26px !important;
  margin-bottom: 0 !important;
}
</style>
